package com.jay.media.music.ui.material

import android.content.Context
import android.os.Handler
import android.util.AttributeSet
import android.util.Log
import android.view.View
import androidx.coordinatorlayout.widget.CoordinatorLayout
import android.view.animation.LinearInterpolator
import androidx.core.view.ViewCompat
import com.google.android.material.floatingactionbutton.FloatingActionButton
import com.jay.media.music.ui.material.ScrollAwareFABBehavior

class ScrollAwareFABBehavior(context: Context?, attributeSet: AttributeSet?) :
    FloatingActionButton.Behavior() {
    private val mHandler: Handler? = Handler()
    override fun onNestedScroll(
        coordinatorLayout: CoordinatorLayout, child: FloatingActionButton,
        target: View, dxConsumed: Int, dyConsumed: Int, dxUnconsumed: Int,
        dyUnconsumed: Int, type: Int, consumed: IntArray
    ) {
        super.onNestedScroll(
            coordinatorLayout,
            child,
            target,
            dxConsumed,
            dyConsumed,
            dxUnconsumed,
            dyUnconsumed,
            type,
            consumed
        )
        Log.d("ScrollAwareFABBehavior", "onNestedScroll() -> $dyConsumed")
        if (dyConsumed > 0) {
            Log.d("ScrollAwareFABBehavior", "Up")
            child.animate()
                .translationY(((child.layoutParams as CoordinatorLayout.LayoutParams).bottomMargin + child.height).toFloat())
                .setInterpolator(LinearInterpolator()).start()
        } else if (dyConsumed < 0) {
            Log.d("ScrollAwareFABBehavior", "down")
            child.animate().translationY(0.0f).setInterpolator(LinearInterpolator()).start()
        }
    }

    override fun onStartNestedScroll(
        coordinatorLayout: CoordinatorLayout,
        child: FloatingActionButton,
        directTargetChild: View,
        target: View,
        axes: Int,
        type: Int
    ): Boolean {
        Log.d("ScrollAwareFABBehavior", "onStartNestedScroll()")
        if (mHandler != null) {
            mHandler.removeMessages(0)
            Log.d("Scrolling", "stopHandler()")
        }
        return axes == ViewCompat.SCROLL_AXIS_VERTICAL
    }

    override fun onStopNestedScroll(
        coordinatorLayout: CoordinatorLayout,
        child: FloatingActionButton,
        target: View,
        type: Int
    ) {
        super.onStopNestedScroll(coordinatorLayout, child, target, type)
        Log.d("ScrollAwareFABBehavior", "onStopNestedScroll()")
        mHandler!!.postDelayed({ onStopNestedScroll(child) }, 1)
    }

    companion object {
        @Synchronized
        fun onStopNestedScroll(floatingActionButton: FloatingActionButton) {
            floatingActionButton.animate().translationY(0.0f).setInterpolator(LinearInterpolator())
                .start()
        }
    }
}